/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.usc.csci538.hw6.screens;

import edu.usc.csci538.hw6.Utils;
import edu.usc.csci538.hw6.data.CalendarEntry;
import edu.usc.csci538.hw6.data.CalendarEntryManager;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author yaoli
 */
public class DayViewList extends List implements CommandListener, OnRenderDisplayable {
    private Calendar currentDate = Calendar.getInstance();
    private Hashtable eventByIndex = new Hashtable();
    private MIDlet midlet;
    private Command exitCommand;
    private Command newCommand;
    private Command editCommand;
    private Command calendarCommand;
    private Command deleteCommand;
    
    public DayViewList() {
        super("Today", List.IMPLICIT);
        currentDate.setTime(new Date(currentDate.getTime().getTime() - 8 * 60*60*1000L));
        exitCommand = new Command("Exit", Command.EXIT, 1);
        newCommand = new Command("New entry", Command.SCREEN, 3);
        editCommand = new Command("Edit entry", Command.SCREEN, 2);
        deleteCommand = new Command("Delete entry", Command.SCREEN, 3);
        calendarCommand = new Command("Calendar View", Command.SCREEN, 4);
        addCommand(exitCommand);
        addCommand(newCommand);
        addCommand(editCommand);
        addCommand(deleteCommand);
        addCommand(calendarCommand);
    }
    public void setMidlet(MIDlet m) {
        midlet = m;
    }
    public void setDate(Date date) {
        currentDate.setTime(date);
    }
    public void onRender() {
        // Make sure we get the commands
        setCommandListener(this);
        
        deleteAll();
        eventByIndex.clear();
        setTitle(Utils.dateAsString(currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)));
        
        // Add previous and next
        append("Previous Day «", null);
        append("                                                             Next Day »", null);
        
        Vector todayEvents = CalendarEntryManager.get().getEntriesForDate(currentDate);
        int indexToSelect = -1;
        for (int i=0; i < todayEvents.size(); i++) {
            CalendarEntry event = (CalendarEntry) todayEvents.elementAt(i);
            int idx = append(getEventString(event), null);
            eventByIndex.put(new Integer(idx), event);
            if (Utils.timeAsInteger(event.getStartTimeHour(), event.getStartTimeMinute(), event.isStartTimeAM()) <
                Utils.timeAsInteger(currentDate.get(Calendar.HOUR), currentDate.get(Calendar.MINUTE), currentDate.get(Calendar.AM_PM) == Calendar.AM)) {
                indexToSelect = i;
            }
        }
        if (todayEvents.isEmpty()) {
            append("<No Events>", null);
        }
        if (indexToSelect + 2 > size()) {
            indexToSelect = 0;
        } else {
            indexToSelect++;
        }
        if (indexToSelect + 2 < size()) {
            setSelectedIndex(indexToSelect + 2, true);
        } else {
            setSelectedIndex(0, true);
        }
    }
    
    private static String getEventString(CalendarEntry e) {
        StringBuffer buffer = new StringBuffer();
        if (e.getSubject().length() > 0) {
            buffer.append(e.getSubject());
        } else {
            buffer.append("No name");
        }
        buffer.append("\n");
        buffer.append(Utils.timeAsString(e.getStartTimeHour(), e.getStartTimeMinute(), e.isStartTimeAM()));
        buffer.append(" - ");
        buffer.append(Utils.timeAsString(e.getEndTimeHour(), e.getEndTimeMinute(), e.isEndTimeAM()));
        return buffer.toString();
    }

    public void commandAction(Command cmd, Displayable source) {
        if (source != this) {
            throw new RuntimeException("Shouldnt be here");
        }
        if (cmd == List.SELECT_COMMAND || cmd == editCommand) {
            if (getSelectedIndex() == 0) {
                // Go back one day
                currentDate.setTime(new Date(currentDate.getTime().getTime() - 24*60*60*1000L));
                onRender();
                setSelectedIndex(0, true);
            } else if (getSelectedIndex() == 1) {
                // Go forward one day
                currentDate.setTime(new Date(currentDate.getTime().getTime() + 24*60*60*1000L));
                onRender();
                setSelectedIndex(1, true);
            } else {
                EventEditForm form = new EventEditForm(midlet,
                  (CalendarEntry)eventByIndex.get(new Integer(getSelectedIndex())), this, null);
                Display.getDisplay(midlet).setCurrent(form);
            }
        } else if (cmd == exitCommand) {
            midlet.notifyDestroyed();
        } else if (cmd == newCommand) {
            final CalendarEntry entry = CalendarEntry.getDefaultEntry();
            EventEditForm form = new EventEditForm(midlet, entry, this,
              new Runnable() {
                public void run() {
                    CalendarEntryManager.get().addEntry(entry);
                }
            });
            Display.getDisplay(midlet).setCurrent(form);
        } else if (cmd == calendarCommand) {
            MonthlyCalendar canvas = new MonthlyCalendar(midlet);
            canvas.setDate(currentDate.getTime());
            Display.getDisplay(midlet).setCurrent(canvas);
        } else if (cmd == deleteCommand) {
            CalendarEntryManager.get().deleteEntry(
                    (CalendarEntry)eventByIndex.get(new Integer(getSelectedIndex())));
            onRender();
        }
    }

    public Displayable getAsDisplayable() {
        return this;
    }
}
